Before Java 8, the only way to partially support closures in Java was by using anonymous inner classes. Java 8 introduced lambdas, which are
significantly more readable and should be used instead.
This rule is automatically disabled when the project’s sonar.java.source
is lower than 8
, as lambda expressions were
introduced in Java 8.
Code examples
Noncompliant code example
myCollection.stream().map(new Function<String,String>() { // Noncompliant, use a lambda expression instead
@Override
public String apply(String input) {
return new StringBuilder(input).reverse().toString();
}
})
...
Compliant solution
myCollection.stream()
.map(input -> new StringBuilder(input).reverse().toString()) // Compliant
...
Noncompliant code example
Predicate<String> isEmpty = new Predicate<String>() { // Noncompliant, use a lambda expression instead
@Override
public boolean test(String myString) {
return myString.isEmpty();
}
};
Compliant solution
Predicate<String> isEmpty = myString -> myString.isEmpty(); // Compliant